Scroll Progress Bar

Storage Classes

In C++, storage classes are used to define the scope, lifetime, and initial value of variables. There are four main storage classes in C++:

Automatic Storage Class (auto):
  • Variables declared as auto have automatic storage duration.
  • They are created when the program enters the scope in which they are declared and destroyed when the scope is exited.
  • The auto keyword is rarely used explicitly because local variables without a storage class specifier are treated as automatic by default.
Program:

int main() {
    auto x = 10; // Equivalent to int x = 10;
    return 0;
}
Register Storage Class (register):
  • Variables declared as register are stored in CPU registers if possible, for faster access.
  • They have the same scope and lifetime as automatic variables.
  • The register keyword is rarely used explicitly, and modern compilers often optimize variable storage automatically.
Program:

int main() {
    register int count = 0; // Suggests the use of a CPU register for 'count'
    return 0;
}
Static Storage Class (static):
  • Variables declared as static have static storage duration.
  • They are created when the program starts and destroyed when the program terminates.
  • Static variables are initialized only once, and their values are retained between function calls.
Program:

void increment() {
    static int counter = 0; // Initialized only once
    counter++;
    std::cout << "Counter: " << counter << std::endl;
}

int main() {
    increment(); // Counter: 1
    increment(); // Counter: 2
    return 0;
}
External or Global Storage Class (extern):

Variables declared as extern have global or external linkage, meaning they it can be accessed across multiple source files. They are typically used to declare variables that are defined in other source files.

Program:

// In File1.
int globalVar = 42;

// In File2.
extern int globalVar; // Declaration of the global variable defined in File1.

In addition to these four main storage classes, C++ also includes other storage class specifiers like mutable, which is used in the context of classes and objects to specify that a member variable it can be modified even if the object is declared as constant.

It's important to choose the appropriate storage class based on the specific requirements of program to control variable scope, lifetime, and initialization behavior. Most variables are declared without an explicit storage class specifier, which makes them automatic by default. Use static for variables that should retain their values between function calls, and use extern for global variables that need to be shared across multiple source files.


question


answer

question2


answer2